package volkov.ja.applogic2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import volkov.ja.applogic.MovieHelper;
import volkov.ja.model.Movie;
import volkov.ja.util.MyProjectException;

public class MovieHelper2 extends DriverBasedHelper implements MovieHelper {

	public MovieHelper2(ApplicationManager2 manager) {
		// super(manager.getWebDriver());
		super(manager);
	}

	@Override
	public void create(Movie movie) {
		app.getNavigationHelper().gotoMovieListPage();
		pages.movieListPage.ensurePageLoaded().clickAddMovieLink()
				.ensurePageLoaded().setTitle(movie.getTitle())
				.setIMDb(movie.getImdb()).setYear(movie.getYear())
				.setNotes(movie.getNotes()).clickSaveButton();
	}

	@Override
	public void delete(Movie movie) {
		app.getNavigationHelper().gotoMovieListPage();
		ArrayList<String> ids = pages.movieListPage.getMovieIds(movie
				.getTitle());
		for (String id : ids) {
			app.getNavigationHelper().gotoMovieViewPage(id);
			String year = pages.movieViewPage.ensurePageLoaded().getYear();
			// if (movie.getYear().equals("") || year.equals(movie.getYear())) {
			if (movie.getYear().equals("") || year.equals(movie.getYear())) {
				pages.movieViewPage.clickRemoveMovieLink();
			}
		}
	}

	@Override
	public List<Movie> search(String title) {
		return search(title, false);
	}
	
	public List<Movie> search(String title, boolean partialSearch) {
		List<Movie> movies = new ArrayList<Movie>();
		app.getNavigationHelper().gotoMovieListPage();
		ArrayList<String> ids = pages.movieListPage.getMovieIds(title, partialSearch);
		for (String id : ids) {
			app.getNavigationHelper().gotoMovieViewPage(id);
			pages.movieViewPage.ensurePageLoaded();
			String movieTitle = pages.movieViewPage.getTitle();
			String year = pages.movieViewPage.getYear();
			String notes = pages.movieViewPage.getNotes();
			Movie m = new Movie().setTitle(movieTitle).setNotes(notes).setYear(year);
			movies.add(m);
		}
		return movies;
	}

	@Override
	public boolean isMovieExisting(Movie movie) {
		app.getNavigationHelper().gotoMovieListPage();
		ArrayList<String> ids = pages.movieListPage.getMovieIds(movie
				.getTitle());
		for (String id : ids) {
			app.getNavigationHelper().gotoMovieViewPage(id);
			String year = pages.movieViewPage.ensurePageLoaded().getYear();
			if (movie.getYear().equals("") || year.equals(movie.getYear())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean isMovieAbsent(Movie movie) {
		app.getNavigationHelper().gotoMovieListPage();
		if (pages.movieListPage.getMovieIds(movie.getTitle()).size() == 0) {
			return true;
		}
		return false;
	}

}
